package come.example.pagetransformer.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.util.Log;

import java.util.ArrayList;

public class RandomTextView extends AppCompatTextView {
    private static final String TAG = RandomTextView.class.getSimpleName();

    //高位快
    public static final int SCROLL_TYPE_HIGH_FAST = 0;
    //高位慢
    public static final int SCROLL_TYPE_HIGH_SLOW = 1;
    //速度相同
    public static final int SCROLL_TYPE_SAME = 2;
    //用户自定义速度
    public static final int SCROLL_TYPE_CUSTOMIZE = 3;
    //偏移速度类型
    private int offSetSpeedType;

    //   滚动总行数 可设置
    private int maxScrollLines = 10;
    //   当前字符串长度
    private int currentStringLength = 0;
    //   当前text
    private String text;

    //滚动速度数组
    private int[] scrollSpeedArray;
    //总滚动距离数组
    private int[] totalScrollDistanceArray;
    //滚动完成判断
    private int[] scrollOverLine;

    private Paint paint;
    //第一次绘制
    private boolean firstDraw = true;
    //滚动中
    private boolean drawing = true;

    //text int值列表
    private ArrayList<Integer> arrayListText;

    //字体宽度
    private float textWidth;

    //基准线
    private int baseline;

    private int measuredHeight;


    public RandomTextView(Context context) {
        super(context);
    }

    public RandomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public RandomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //按系统提供的类型滚动
    public void setScrollType(int scrollType) {
        this.text = getText().toString();
        totalScrollDistanceArray = new int[text.length()];
        scrollOverLine = new int[text.length()];
        scrollSpeedArray = new int[text.length()];
        switch (scrollType) {
            case SCROLL_TYPE_HIGH_FAST:
                for (int i = 0; i < text.length(); i++) {
                    scrollSpeedArray[i] = 20 - i;
                }
                break;
            case SCROLL_TYPE_HIGH_SLOW:
                for (int i = 0; i < text.length(); i++) {
                    scrollSpeedArray[i] = 15 + i;
                }
                break;
            case SCROLL_TYPE_SAME:
            default: SCROLL_TYPE_SAME:
                for (int i = 0; i < text.length(); i++) {
                    scrollSpeedArray[i] = 15;
                }
        }
    }

    //自定义滚动速度数组
    public void setScrollSpeedArray(int[] list) {
        this.text = getText().toString();
        totalScrollDistanceArray = new int[list.length];
        scrollOverLine = new int[list.length];
        scrollSpeedArray = list;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        Log.d(TAG, "onDraw");
        if (firstDraw) {
            firstDraw = false;
            super.onDraw(canvas);
            paint = getPaint();
            Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
            measuredHeight = getMeasuredHeight();
            Log.d(TAG, "onDraw: " + measuredHeight);
            baseline = (measuredHeight - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
            float[] widths = new float[4];
            paint.getTextWidths("9999", widths);
            textWidth = widths[0];
            invalidate();
        }
        drawNumber(canvas);
    }

    //绘制
    private void drawNumber(Canvas canvas) {
        for (int j = 0; j < currentStringLength; j++) {
            for (int i = 1; i < maxScrollLines; i++) {
                if (i == maxScrollLines - 1 && i * baseline + totalScrollDistanceArray[j] <= baseline) {
                    scrollSpeedArray[j] = 0;
                    scrollOverLine[j] = 1;
                    int auto = 0;
                    for (int k = 0; k < currentStringLength; k++) {
                        auto += scrollOverLine[k];
                    }
                    if (auto == currentStringLength * 2 - 1) {
                        removeCallbacks(task);
                        //修复停止后绘制问题
                        if (this.drawing) invalidate();
                        this.drawing = false;
                    }
                }
                if (scrollOverLine[j] == 0){
                    String text = setBack(arrayListText.get(j), maxScrollLines - i - 1) + "";
                    float x = 0 + textWidth * j;
                    float y = i * baseline + totalScrollDistanceArray[j];
                    drawText(canvas, text, x, y, paint);
                    //canvas.drawText(setBack(arrayListText.get(j), maxScrollLines - i - 1) + "", 0 + textWidth * j, i * baseline + totalScrollDistanceArray[j], paint);
                } else {
                    //定位后画一次就好啦
                    if (scrollOverLine[j] == 1) {
                        scrollOverLine[j]++;
                        String text = arrayListText.get(j) + "";
                        float x = 0 + textWidth * j;
                        drawText(canvas, text, x, baseline, paint);
                        // canvas.drawText(arrayListText.get(j) + "", 0 + textWidth * j, baseline, paint);
                    }
                    //break;
                }
            }
        }
    }

    //设置上方数字0-9递减
    private int setBack(int c, int back) {
        if (back == 0) return c;
        back = back % 10;
        int re = c - back;
        if (re < 0) re = re + 10;
        return re;
    }

    //开始滚动
    public void start() {
        this.text = getText().toString();
        currentStringLength = text.length();
        arrayListText = getList(text);
        postDelayed(task, 17);
        drawing = true;
    }

    public void setMaxScrollLines(int lines) {
        this.maxScrollLines = lines;
    }

    private ArrayList<Integer> getList(String s) {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        for (int i = 0; i < s.length(); i++) {
            String ss = s.substring(i, i + 1);
            int a = Integer.parseInt(ss);
            arrayList.add(a);
        }
        return arrayList;
    }

    public void destroy() {
        drawing = false;
        removeCallbacks(task);
    }

    private final Runnable task = new Runnable() {
        public void run() {
            if (drawing) {
                postDelayed(this, 20);
                for (int j = 0; j < currentStringLength; j++) {
                    totalScrollDistanceArray[j] -= scrollSpeedArray[j];
                }
                invalidate();
            }
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        destroy();
    }

    private void drawText(Canvas mCanvas, String text, float x, float y, Paint p) {
        if (y >= -measuredHeight && y <= 2 * measuredHeight)
            mCanvas.drawText(text + "", x, y, p);
        else return;
    }
}
